package com.yonyou.iuap.controller.app;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.yonyou.iuap.pub.DateUtil;
import com.yonyou.iuap.pub.JsonUtils;
import com.yonyou.iuap.shell.entity.exp.AttachementPoJo;
import com.yonyou.iuap.shell.entity.exp.KmAttPoJo;
import com.yonyou.iuap.shell.entity.exp.KmpublishPoJo;
import com.yonyou.iuap.shell.entity.exp.KnowledgeAttachmentPoJo;
import com.yonyou.iuap.shell.pub.IFileType;
import com.yonyou.iuap.shell.pub.RequestDto;
import com.yonyou.iuap.shell.pub.ResultDto;
import com.yonyou.iuap.shell.service.intf.IKmPublishService;
import com.yonyou.iuap.shell.service.intf.IKnowledgeCategoryService;
import com.yonyou.iuap.shell.util.ShellUtils;
import com.yonyou.iuap.utils.PropertyUtil;

@Controller
@RequestMapping("/kmpublish")
public class KmPublishController {
	private final Logger logger = (Logger) LoggerFactory.getLogger(getClass());
	private long start,end;
	public KmPublishController(){
	}
	@Autowired
	private IKmPublishService kmPublishServiceImpl;
	@Autowired
	private IKnowledgeCategoryService iKnowledgeCategoryService;
//	老接口，当附件很多时效率很低
	@RequestMapping("/App/queryKnowledgeAttByPK")
	public @ResponseBody String queryKnowledgeAttByPK(@RequestBody HashMap map,HttpServletRequest request,HttpServletResponse response){
		start=System.currentTimeMillis();
		ResultDto rsDto = new ResultDto();
		String pk_publish = map.get("pk_publish")==null?null:map.get("pk_publish").toString();
		String pk_user = map.get("pk_user")==null?null:map.get("pk_user").toString();
		if(StringUtils.isEmpty(pk_publish)){
			rsDto.setStatus(1);
			rsDto.setMessage("查询条件不全!");
		}else{
			Map<String, String> parmMap = new HashMap<String, String>();
			parmMap.put("pk_km_publish", pk_publish);
			parmMap.put("pk_user", pk_user);
//			分开查询附件
//			rsDto = kmPublishServiceImpl.queryKnowledgeattbypk(parmMap);
			rsDto = kmPublishServiceImpl.queryKnowledgeAttachment(parmMap);
			//构建前台json
			buildKmAttJson(rsDto);
			List<KnowledgeAttachmentPoJo> kmpojo = (List<KnowledgeAttachmentPoJo>) rsDto.getData();
			//给PC端用，返回一节类别下面的所有子集 
			 String str="sealmark='Y' and  fw_parent in (select pk_knowledge_category  from shell_bd_knowledge_category where  fw_level=0 and sealmark='Y') and  fw_parent='"+(kmpojo==null || kmpojo.size()==0?"NULL":kmpojo.get(0).getKm_type()==null?"Null":kmpojo.get(0).getKm_type())+"'";  
			//String sql="fw_parent= '"+(kmpojo==null || kmpojo.size()==0?"NULL":kmpojo.get(0).getKm_type()==null?"Null":kmpojo.get(0).getKm_type())+"'";
			ResultDto rsDto2 =iKnowledgeCategoryService.selectByCondition(str);
			if(rsDto2!=null && rsDto2.getData()!=null ){
				List list2 = (List) rsDto2.getData();
				rsDto.setData1(list2==null || list2.size()==0?null:list2);
			}
		}
		end=System.currentTimeMillis();
		logger.info("queryKnowledgeAttByPK"+String.valueOf(end-start));
		return JsonUtils.toJsonStr(rsDto);
	}
//	单独查询知识内容
	@RequestMapping("/App/queryKnowledgeByPK")
	public @ResponseBody String queryKnowledgeByPK(@RequestBody HashMap map,HttpServletRequest request,HttpServletResponse response){
		start=System.currentTimeMillis();
		ResultDto rsDto = new ResultDto();
		String pk_publish = map.get("pk_publish")==null?null:map.get("pk_publish").toString();
		if(StringUtils.isEmpty(pk_publish)){
			rsDto.setStatus(1);
			rsDto.setMessage("查询条件不全!");
		}else{
			Map<String, String> parmMap = new HashMap<String, String>();
			parmMap.put("pk_km_publish", pk_publish);
			parmMap.put("pk_user", map.get("pk_user").toString());
			rsDto = kmPublishServiceImpl.queryKnowledgebypk(parmMap);
			//构建前台json
			buildKmAttJson(rsDto);
			List<KnowledgeAttachmentPoJo> kmpojo = (List<KnowledgeAttachmentPoJo>) rsDto.getData();
			//给PC端用，返回一节类别下面的所有子集 
			 String str="sealmark='Y' and  fw_parent in (select pk_knowledge_category  from shell_bd_knowledge_category where  fw_level=0 and sealmark='Y') and  fw_parent='"+(kmpojo==null || kmpojo.size()==0?"NULL":kmpojo.get(0).getKm_type()==null?"Null":kmpojo.get(0).getKm_type())+"'";  
			//String sql="fw_parent= '"+(kmpojo==null || kmpojo.size()==0?"NULL":kmpojo.get(0).getKm_type()==null?"Null":kmpojo.get(0).getKm_type())+"'";
			ResultDto rsDto2 =iKnowledgeCategoryService.selectByCondition(str);
			if(rsDto2!=null && rsDto2.getData()!=null ){
				List list2 = (List) rsDto2.getData();
				rsDto.setData1(list2==null || list2.size()==0?null:list2);
			}
		}
		end=System.currentTimeMillis();
		logger.info("queryKnowledgeByPK"+String.valueOf(end-start));
		return JsonUtils.toJsonStr(rsDto);
	}
	@RequestMapping("/App/queryAttByPK")
	public @ResponseBody String queryAttByPK(@RequestBody HashMap map,HttpServletRequest request,HttpServletResponse response){
		start=System.currentTimeMillis();
		ResultDto rsDto = new ResultDto();
		String pk_publish = map.get("pk_publish")==null?null:map.get("pk_publish").toString();
		if(StringUtils.isEmpty(pk_publish)){
			rsDto.setStatus(1);
			rsDto.setMessage("查询条件不全!");
		}else{
			Map<String, String> parmMap = new HashMap<String, String>();
			parmMap.put("pk_km_publish", pk_publish);
			rsDto = kmPublishServiceImpl.queryKnowledgeattbypk(parmMap);
			//构建前台json
			buildKmAttJson(rsDto);
		}
		end=System.currentTimeMillis();
		logger.info("queryAttByPK接口调用时间"+String.valueOf(end-start));
		return JsonUtils.toJsonStr(rsDto);
	}
/*//	根据用户名及关键字查知识
	@RequestMapping("/App/queryKnowledgeAttByKey")
	public @ResponseBody String queryKnowledgeAttByKey(@RequestBody HashMap map,HttpServletRequest request,HttpServletResponse response){
		ResultDto rsDto = new ResultDto();
		String pk_user = map.get("pk_user")==null?null:map.get("pk_user").toString();
		String key_value = map.get("key")==null?null:map.get("key").toString();
		if(StringUtils.isEmpty(pk_user) || StringUtils.isEmpty("pk_publish")){
			rsDto.setStatus(1);
			rsDto.setMessage("查询条件不全!");
		}else{
			String whereSql = getQueryWhere(key_value);
			Map<String, String> parmMap = new HashMap<String, String>();
			parmMap.put("pk_user", pk_user);
			parmMap.put("key", whereSql);
			rsDto = kmPublishServiceImpl.queryKnowledgeAttachment(parmMap);
			//构建前台json
			buildKmAttJson(rsDto);
		}
		return JsonUtils.toJsonStr(rsDto);
	}*/
	/**
	 * 构建关键查询的条件
	 * @param key_value
	 * @return
	 */
	private String getQueryWhere(String key_value){
		StringBuffer sb = new StringBuffer("");
		sb.append("  (");
		if(!StringUtils.isEmpty(key_value)){
			if(key_value.indexOf(",")<0){
				sb.append("upper(a.publish_key) like upper('%"+key_value+"%')  ");
			}else{
				String[] str_keys = key_value.split(",");
				for(String str:str_keys){
					sb.append(" upper(a.publish_key) like upper('%"+str+"%')").append(" or");
				}
				sb.delete(sb.toString().length()-2, sb.toString().length());
				sb.append(")");
			}
		}
		return sb.toString();
	}
	/**
	 * 构建前台需要json格式
	 * @param rsDto
	 */
	private void buildKmAttJson(ResultDto rsDto){
		if(rsDto!=null && rsDto.getData()!=null){
			List<KmAttPoJo> listvo = (List<KmAttPoJo>) rsDto.getData();
			Map<String, List<AttachementPoJo>> map_pic = new HashMap<String, List<AttachementPoJo>>();
			Map<String, List<AttachementPoJo>> map_oth = new HashMap<String, List<AttachementPoJo>>();
			List<KnowledgeAttachmentPoJo> listPoJo = new ArrayList<KnowledgeAttachmentPoJo>();
			for(KmAttPoJo vo : listvo){
				AttachementPoJo attpojo = new AttachementPoJo();
				attpojo.setFilename(vo.getFilename());
				attpojo.setFilesize(ShellUtils.getFileSize(vo.getFilesize()==null?0:vo.getFilesize().longValue()));
//				attpojo.setFileurl(getUrl(vo));
				attpojo.setFileurl(vo.getFileurl());
				attpojo.setFname(vo.getFname());
				attpojo.setPk_attachment(vo.getPk_attachment());
				attpojo.setPk_business(vo.getPk_km_publish());
				attpojo.setUpload_type(vo.getUpload_type());
				if(!StringUtils.isEmpty(vo.getFile_ts())){
					attpojo.setAtt_year(DateUtil.getYear(vo.getFile_ts()));
					attpojo.setAtt_month(DateUtil.getMonth(vo.getFile_ts()));
					attpojo.setAtt_day(DateUtil.getDay(vo.getFile_ts()));
				}
				if(vo.getFileMeasure()!=null&&vo.getFileMeasure().length()>1){
					attpojo.setFile_measure(vo.getFileMeasure());
				}
				
				if(map_pic.get(vo.getPk_km_publish())!=null || map_oth.get(vo.getPk_km_publish())!=null){
					if(!StringUtils.isEmpty(vo.getPk_attachment())){
						
						if(attpojo.getUpload_type()==IFileType.PIC){
							List<AttachementPoJo> pojoList = map_pic.get(vo.getPk_km_publish());
							if(pojoList==null){
								pojoList =  new ArrayList<AttachementPoJo>();
							}
							pojoList.add(attpojo);
						}else{
							List<AttachementPoJo> pojoList = map_oth.get(vo.getPk_km_publish());
							if(pojoList==null){
								pojoList =  new ArrayList<AttachementPoJo>();
							}
							pojoList.add(attpojo);
						}
					}
					
				}else{
					KnowledgeAttachmentPoJo pojo = new KnowledgeAttachmentPoJo();
					pojo.setKm_type(vo.getKm_type());
					pojo.setKm_type_name(vo.getKm_type_name());
					pojo.setKm_type2(vo.getKm_type2());
					pojo.setKm_type_name2(vo.getKm_type_name2());
					pojo.setPk_km_publish(vo.getPk_km_publish());
					pojo.setPublish_key(vo.getPublish_key());
					pojo.setPublish_memo(vo.getPublish_memo());
					pojo.setPublish_title(vo.getPublish_title());
					pojo.setPublish_time(vo.getPublish_time());
					pojo.setStudioUrl(vo.getStudioUrl());
					if(!StringUtils.isEmpty(vo.getPublish_time())){
						pojo.setPublish_year(DateUtil.getYear(vo.getPublish_time()));
						pojo.setPublish_month(DateUtil.getMonth(vo.getPublish_time()));
						pojo.setPublish_day(DateUtil.getDay(vo.getPublish_time()));
					}
					pojo.setPk_publish_user(vo.getPk_publish_user());
					pojo.setPublish_user_name(vo.getPublish_user_name());
					pojo.setPk_favorite(vo.getPk_favorite());
					if(!StringUtils.isEmpty(vo.getPk_attachment())){
						List<AttachementPoJo> attList_pic = new ArrayList<AttachementPoJo>();
						List<AttachementPoJo> attList_oth = new ArrayList<AttachementPoJo>();
						if(attpojo.getUpload_type()==IFileType.PIC){
							attList_pic.add(attpojo);
						}else{
							attList_oth.add(attpojo);
						}
						
						pojo.setAchementList_pic(attList_pic);
						pojo.setAchementList_oth(attList_oth);
						map_pic.put(vo.getPk_km_publish(), attList_pic);
						map_oth.put(vo.getPk_km_publish(), attList_oth);
					}
					
					listPoJo.add(pojo);
				}
			}
			rsDto.setData(listPoJo);
		}
	}
	@RequestMapping(value="App/queryKmpublishPoJoLike", method=RequestMethod.POST)
	public @ResponseBody String queryKmpublishPoJoLike(@RequestBody HashMap parMap,HttpServletRequest request,HttpServletResponse response){
		start=System.currentTimeMillis();
		ResultDto rsDto = new ResultDto();
		StringBuffer str=new StringBuffer();
		String productkey=parMap.get("productkey")==null?"":parMap.get("productkey").toString();
		String industrykey=parMap.get("industrykey")==null?"":parMap.get("industrykey").toString();
		String likeName=parMap.get("likeName")==null?"":parMap.get("likeName").toString();
		String km_type = parMap.get("kmType")==null?"":parMap.get("kmType").toString();
		str.append(" 1=1 ");
//		行业关键字多选且是并集
		if(!StringUtils.isEmpty(industrykey)){
			String[] list=industrykey.split(";");
			str.append(" and (");
			for(String key:list){
				str.append(" upper(c.publish_key) like upper('%"+key+"%')  or");
			}
			str.delete(str.length()-2, str.length());
			str.append(" ) ");
		}
//		产品关键字多选且是并集
		if(!StringUtils.isEmpty(productkey)){
			String[] list=productkey.split(";");
			str.append(" and ( ");
			for(String key:list){
				str.append(" upper(c.publish_key) like upper('%"+key+"%')  or");
			}
			str.delete(str.length()-2, str.length());
			str.append(" ) ");
		}
//		直接搜索
		if(!StringUtils.isEmpty(likeName)){
//			在汉字与英文字母中间插入空格
			likeName=likeName.replaceAll("([\\u4e00-\\u9fa5])(\\w)", "$1 $2");
//			在数字和字母间插入空格
			likeName=likeName.replaceAll("([0-9])([A-Za-z])", "$1 $2");
			String[] keylist=likeName.trim().split("\\s+");
			for(String key:keylist){
				str.append(" AND upper(c.publish_key) like upper('%"+key+"%')");
			}
		}
//		类别条件
		if(!StringUtils.isEmpty(km_type)){
			String s="(select t.pk_knowledge_category from SHELL_BD_KNOWLEDGE_CATEGORY t "
					+ "where t.pk_knowledge_category='"+km_type+"' or t.fw_parent='"+km_type+"')";
			str.append(" AND c.km_type in "+s);
		}
		
		RequestDto reqDto = new RequestDto();
		reqDto.setParams(str.toString());
		reqDto.setPageNum((Integer.valueOf(parMap.get("pageNum").toString())-1)*Integer.valueOf(parMap.get("pageSize").toString()));
		reqDto.setPageSize(Integer.valueOf(parMap.get("pageSize").toString()));
		logger.info("queryKmpublishPoJoLike接口参数"+JsonUtils.toJsonStr(reqDto));
		rsDto=kmPublishServiceImpl.queryKmpublishPoJoLike(reqDto);
		rsDto.setStatus(0);
		rsDto.setMessage("数据查询成功!");
		end=System.currentTimeMillis();
		logger.info("queryKmpublishPoJoLike接口调用时间"+String.valueOf(end-start));
		return JsonUtils.toJsonStr(rsDto);
	}
	/**
	 * 知识数量统计
	 * */
	@RequestMapping(value="queryKmpublishPoJoCount", method=RequestMethod.POST)
	public @ResponseBody String queryKmpublishPoJoCount(@RequestBody HashMap parMap,HttpServletRequest request,HttpServletResponse response){
		start=System.currentTimeMillis();
		List<KmpublishPoJo> pojo=kmPublishServiceImpl.CountKmpublishPoJo();
		end=System.currentTimeMillis();
		logger.info("queryKmpublishPoJoCount接口调用时间"+String.valueOf(end-start));
		return JsonUtils.toJsonStr(pojo);
	}
	
}
